import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flui/flui.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:fzcgx_app/common/adapter_utils.dart';
import 'package:fzcgx_app/common/color_utils.dart';
import 'package:fzcgx_app/network/http.dart';
import 'package:fzcgx_app/network/urls.dart';
import 'package:fzcgx_app/router/routes.dart';
import 'package:fzcgx_app/ui/base/base_view_model.dart';
import 'package:fzcgx_app/ui/my/factory/model/certificates_upload_model.dart';
import 'package:image_picker/image_picker.dart';

class CertificatesUploadViewModel extends BaseViewModel {
  CertificatesUploadModel model;
  final picker = ImagePicker();
  CertificatesUploadViewModel() {
    this.setState(ViewState.Loading);
  }
  void requestApi() {
    Http.instance.post<CertificatesUploadModel>(
        'app/call/getusers_zhengjianshangchuan_gc', null, onSuccess: (data) {
      if (data != null) {
        model = data;

        this.setState(ViewState.Success);
      } else {
        this.setState(ViewState.Empty);
      }
    }, onError: (error) {}, onFail: (fail) {});
  }

  void selectPhoto(BuildContext context, int photoType) async {
    int result = await showModalBottomSheet(
      isScrollControlled: true,
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadiusDirectional.only(
          topStart: Radius.circular(10),
          topEnd: Radius.circular(10),
        ),
      ),
      builder: (BuildContext context) {
        return StatefulBuilder(builder: (context1, state) {
          return IntrinsicWidth(
              stepHeight: 1.0,
              child: SingleChildScrollView(
                child: Container(
                  padding: EdgeInsets.only(
                      bottom: MediaQuery.of(context).viewInsets.bottom),
                  child: Column(
                    children: [
                      Container(
                        color: Color.fromRGBO(240, 240, 248, 1),
                        height: 60,
                        padding: EdgeInsets.symmetric(
                            horizontal: AdapterUtils.getWidth(12)),
                        child: Row(
                          children: <Widget>[
                            Text(
                              '提示',
                              style: TextStyle(
                                  fontSize: AdapterUtils.getSp(16),
                                  color: ColorUtils.defaultColor,
                                  fontWeight: FontWeight.w500),
                            ),
                            Spacer(),
                            InkWell(
                              onTap: () => Routes.goBack(context),
                              child: Icon(Icons.close,
                                  color: ColorUtils.text2Color),
                            )
                          ],
                        ),
                      ),
                      InkWell(
                        onTap: () => Navigator.pop(context, 1),
                        child: Container(
                          color: Colors.white,
                          child: ListTile(
                            title: Text(
                              '从相册选择',
                              style: TextStyle(
                                  fontSize: AdapterUtils.getSp(14),
                                  color: ColorUtils.text1Color,
                                  fontWeight: FontWeight.w400),
                            ),
                          ),
                        ),
                      ),
                      InkWell(
                        onTap: () => Navigator.pop(context, 2),
                        child: Container(
                          color: Colors.white,
                          child: ListTile(
                            title: Text(
                              '拍照',
                              style: TextStyle(
                                  fontSize: AdapterUtils.getSp(14),
                                  color: ColorUtils.text1Color,
                                  fontWeight: FontWeight.w400),
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ));
        });
      },
    );
    if (result == null) {
      return;
    }
    if (result == 1) {
      getImage(1, photoType);
    } else {
      getImage(2, photoType);
    }
  }

  Future<Null> getImage(int source, int photoType) async {
    final selectedFile = await picker.getImage(
        source: source == 1 ? ImageSource.gallery : ImageSource.camera);
    if (selectedFile != null) {
      String path = selectedFile.path;
      var name = path.substring(path.lastIndexOf("/") + 1, path.length);
      //var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
      FormData formData = new FormData.fromMap({
        "name": "file",
        'enctype': "multipart/form-data",
        "img": await MultipartFile.fromFile(path, filename: name),
      });

      Dio dio = new Dio();
      dio.interceptors
          .add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
        dio.lock();

        var authorization = SpUtil.getString('token');
        options.headers["token"] = authorization;

        dio.unlock();
        return options;
      }));
      var dismiss = FLToast.showLoading(text: '正在上传');
      var respone = await dio.post<String>(
        Urls.debug_base_url + Urls.upload_photo,
        data: formData,
      );
       dismiss();
      if (respone.statusCode == 200) {
        Map imgData = jsonDecode(respone.data);
        print('uu:$imgData');
        String field = '';
        if (photoType == 1) {
          field = 'xingxiangzhao';
        } else if (photoType == 2) {
          field = 'shenfenzhengzhengmian';
        } else if (photoType == 3) {
          field = 'shenfenzhengfanmian';
        } else if (photoType == 4) {
          field = 'jiangzhuang';
        } else if (photoType == 5) {
          field = 'jiehunzheng';
        } else if (photoType == 6) {
          field = 'jiashizheng';
        } else if (photoType == 7) {
          field = 'zuzhijiegoudaimazhao';
        } else if (photoType == 8) {
          field = 'yingyezhizhao';
        } else if (photoType == 9) {
          field = 'shuiwudengjizheng';
        } else if (photoType == 10) {
          field = 'zulinhetongzhao';
        } else if (photoType == 11) {
          field = 'geleixukezheng';
        } else if (photoType == 12) {
          field = 'geleirongyu';
        } else if (photoType == 13) {
          field = 'fangchanzheng';
        }
        var dismiss = FLToast.showLoading(text: '正在设置');
        Http.instance.post('app/call/setusers_zhengjianshangchuan_gc', {
          'field': field,
          'src': imgData['data']['img']['img'].toString()
        }, onSuccess: (data) {
          dismiss();
          FLToast.success(text: '上传成功');
          requestApi();
        }, onError: (error) {}, onFail: (fail) {});
      }
    }
  }
}
